﻿using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Threading.Tasks;
using MDT_MonitorModel;

namespace MDT_Metro_monitoring
{
    public class ODataSampleViewModel
    {
        

        public ODataSampleViewModel(string uri, string port)
        {

            if (port != "")
            {
                try
                {
                    Uri srv = new Uri("http://" + uri + ":" + port + "/MDTMonitorData");
                }
                catch (System.FormatException e)
                {
                    throw new Exception(e.Message);
                }
                catch (Exception)
                {

                }
                this.Context = new MDT_MonitorEntities(new Uri("http://" + uri + ":" + port + "/MDTMonitorData"));
            }
        }

        public MDT_MonitorEntities Context { get; private set; }

        public Computer SelectedComputer
        {
            get;
            set;
        }

        public async Task<IEnumerable<Computer>> LoadComputersAsync()
        {
            var query = (DataServiceQuery<Computer>)this.Context.Computers.Take(50);

            var downloadedComputers = await query.ExecuteAsync();

            return downloadedComputers;
        }

        public async Task<IEnumerable<Computer>> LoadComputerAsync(Computer computer)
        {
            if (this.Context.GetEntityDescriptor(computer) == null)
            {
                this.Context.AttachTo("Computers", computer);
            }
            else
            {
                this.Context.Detach(computer);
                this.Context.AttachTo("Computers", computer);
            }

            Uri requestUri = new Uri(string.Format("Computers('{0}')", computer.ID), UriKind.Relative);
            var tileTitles = await this.Context.ExecuteAsync<Computer>(requestUri);

            return tileTitles;
        }
    }
}
